package com.ysxsoft.wdg.ui.activity.center_zy;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.socks.library.KLog;
import com.ysxsoft.wdg.R;
import com.ysxsoft.wdg.adapter.center_zy.GoodsRulesAdapter;
import com.ysxsoft.wdg.bean.BaseBean;
import com.ysxsoft.wdg.bean.zy.GoodsBean;
import com.ysxsoft.wdg.bean.zy.RuleBean;
import com.ysxsoft.wdg.net.ApiHelper;
import com.ysxsoft.wdg.net.CallbackCode;
import com.ysxsoft.wdg.ui.activity.center_st.StGoodsConfirmActivity;
import com.ysxsoft.wdg.ui.activity.login.LoginValid;
import com.ysxsoft.wdg.util.ToastUtils;
import com.ysxsoft.wdg.util.delayaction.Action;
import com.ysxsoft.wdg.util.delayaction.SingleCall;
import com.ysxsoft.wdg.util.sp.SharePrefUtils;
import com.ysxsoft.wdg.util.statusbar.StatusBarUtil;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

public class GoodsRulesActivity extends Activity {


    public static final String JUMP_CODE = "cart_buy";

    @BindView(R.id.btn_finish)
    View btnFinish;
    @BindView(R.id.iv_goods)
    ImageView ivGoods;
    @BindView(R.id.tv_money)
    TextView tvMoney;
    @BindView(R.id.tv_num)
    TextView tvNum;
    @BindView(R.id.tv_rules)
    TextView tvRules;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.edit_goods_sub)
    ImageView ivGoodsSub;
    @BindView(R.id.edit_goods_num)
    TextView tvGoodsNum;
    @BindView(R.id.edit_goods_plus)
    ImageView ivGoodsPlus;
    @BindView(R.id.btn_commit)
    TextView btnCommit;
    @BindView(R.id.tv_buy_num)
    TextView tvBuyNum;
    private boolean isStGood=false;

    private boolean isBuy = false;
    public static final int up_bottom = 0, up_top = 1;
    private String goodsid = "", priceOne="",rules ="",code="",uid="",product_rule_id="";

    private GoodsBean product;
    private ApiHelper mApiHelper;

    private List<RuleBean> list;
    private GoodsRulesAdapter mAdapter;
    private int buyNum = 1, totalNum = 100, groupSize = 0;

    private Unbinder mUnbinder;

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case up_bottom:
                    tvGoodsNum.setText("" + buyNum);
                    break;
                case up_top:
                    tvNum.setText("库存" + totalNum + "件");
                    tvMoney.setText(getString(R.string.price_rmb,priceOne));
                    tvRules.setText(rules);
                    break;
            }
        }
    };



    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_goods_rules);
        mUnbinder = ButterKnife.bind(this);
        mApiHelper = new ApiHelper();
        initData();
        setListener();
    }


    protected void initData() {
        StatusBarUtil.setStatusBarTextColor(this, true);

        uid = SharePrefUtils.getUserId();
        list = new ArrayList<>();

        Intent intent = getIntent();
        code = intent.getStringExtra(JUMP_CODE);
        if (code.equals("cart")){//购物车
            isBuy = false;
            btnCommit.setText("加入购物车");
        }else if (code.equals("buy")){//立即购买
            isBuy = true;
            btnCommit.setText("立即购买");
        }

        product = intent.getParcelableExtra("goodsBean");
        list = intent.getParcelableArrayListExtra("rules");
        isStGood=intent.getBooleanExtra("isStGood",false);//是否实体订单选择规格

        totalNum = Integer.parseInt(product.getStore());
        priceOne = product.getPrice();

        groupSize= list.size();
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        mAdapter = new GoodsRulesAdapter(this, list);
        recyclerView.setAdapter(mAdapter);

        goodsid = product.getId();

        Glide.with(GoodsRulesActivity.this).load(product.getPic()).into(ivGoods);


        handler.sendEmptyMessage(up_top);
        handler.sendEmptyMessage(up_bottom);

    }




    protected void setListener() {
        mAdapter.setOnChildClickListener(new GoodsRulesAdapter.OnChildClickListener() {
            @Override
            public void onChildClick(int groupPosition, int childPosition) {
                chooseRule();
            }
        });
    }



    @OnClick({R.id.btn_finish,R.id.iv_finish, R.id.edit_goods_sub,
            R.id.edit_goods_plus, R.id.btn_commit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_finish:
            case R.id.iv_finish:
                finish();
                break;
            case R.id.edit_goods_sub:
                if (buyNum <= 1) {
                    return;
                } else {
                    buyNum--;
                }
                handler.sendEmptyMessage(up_bottom);
                break;
            case R.id.edit_goods_plus:
                if (buyNum >= totalNum) {
                    return;
                } else {
                    buyNum++;
                }
                handler.sendEmptyMessage(up_bottom);
                break;
            case R.id.btn_commit:
                if(hasStore){
                    if (isBuy) {//立即购买
                        if (TextUtils.isEmpty(product_rule_id)) {
                            commit();
                        } else {
                            if(isStGood){
                                //实体确认订单
                                toStConfirmActivity();
                            }else{
                                //自营确认订单
                                toConfirmActivity();
                            }
                        }
                    }else {//加入购物车
                        if (TextUtils.isEmpty(product_rule_id)) {
                            commit();
                        }else {
                            addCart();
                        }
                    }
                }else{
                    ToastUtils.showToast("抱歉！您选择的商品规格卖完了！");
                }
                break;
        }
    }

    @NonNull
    private String getRulesIds() {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < groupSize; i++) {
            List<RuleBean.SubBean> content = list.get(i).getSub();
            for (int j = 0; j < content.size(); j++) {
                RuleBean.SubBean contentBean = content.get(j);
                if (contentBean.isSelected()) {
                    sb.append(contentBean.getId());
                }
            }

            if (i < groupSize - 1) {
                sb.append(",");
            }
        }

        KLog.e(sb.toString()+"");
        return sb.toString()+"";
    }

    private String getRuleName(){
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < groupSize; i++) {
            List<RuleBean.SubBean> content = list.get(i).getSub();
            for (int j = 0; j < content.size(); j++) {
                RuleBean.SubBean contentBean = content.get(j);
                if (contentBean.isSelected()) {
                    sb.append(contentBean.getTitle());
                }
            }

            if (i < groupSize - 1) {
                sb.append(",");
            }
        }

        KLog.e(sb.toString()+"");
        return sb.toString()+"";
    }



    private void chooseRule() {
        final String ruleid = getRulesIds();
        mApiHelper.chooseRule(goodsid, ruleid, new Observer<BaseBean<GoodsBean>>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(BaseBean<GoodsBean> baseBean) {

                if (baseBean.getCode().equals(CallbackCode.SUCCESS)) {
                    GoodsBean data = baseBean.getData();

                    totalNum = Integer.parseInt(data.getStore());
                    priceOne = data.getPrice();
                    rules = data.getRule_name();
                    product_rule_id = data.getProduct_rule_id();
                    handler.sendEmptyMessage(up_top);
                }
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        });
    }

    private boolean hasStore=true;
    private void commit(){
        final String ruleid = getRulesIds();
        mApiHelper.chooseRule(goodsid, ruleid, new Observer<BaseBean<GoodsBean>>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(BaseBean<GoodsBean> baseBean) {

                if (baseBean.getCode().equals(CallbackCode.SUCCESS)) {
                    GoodsBean data = baseBean.getData();

                    if(data.getStore()!=null&&!"".equals(data.getStore())&&"0".equals(data.getStore())){
                        hasStore=true;
                    }else{
                        hasStore=false;
                    }

                    product_rule_id =data.getProduct_rule_id();
                    if (isBuy) {
                        if(isStGood){
                            //实体商品
                            toStConfirmActivity();
                        }else{
                            //自营商品
                            toConfirmActivity();
                        }
                    }else {
                        addCart();
                    }
                }
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        });
    }

    private void toConfirmActivity() {
        ZyGoodsConfirmActivity.start(GoodsRulesActivity.this,product_rule_id,buyNum+"");
        finish();
    }

    private void toStConfirmActivity() {
        Intent intent=new Intent();
        intent.putExtra("buyNum",buyNum);
        intent.putExtra("ruleId",product_rule_id);
        intent.putExtra("priceOne",priceOne);
        intent.putExtra("rules",getRuleName());
        setResult(RESULT_OK,intent);
        finish();
    }

    private void addCart(){
        KLog.e("uid="+uid+",product_rule_id="+product_rule_id+",buyNum="+buyNum);
        mApiHelper.addCart(uid, product_rule_id, buyNum + "", new Observer<BaseBean>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(BaseBean baseBean) {
                ToastUtils.showToast(baseBean.getMs());
                if (baseBean.getCode().equals(CallbackCode.SUCCESS)){
                    finish();
                }
            }

            @Override
            public void onError(Throwable e) {
                ToastUtils.showToast("请稍后再试");
            }

            @Override
            public void onComplete() {

            }
        });
    }



    @Override
    protected void onDestroy() {
        super.onDestroy();
        mUnbinder.unbind();
    }
}
